Meteor.publish("users", function(location) {
  if (this.userId) {
    if (!Roles.userIsInRole(this.userId, 'driver')) {
      if (!location)
        return;
      return Meteor.users.find({
        roles: {
          $in: ['driver']
        },
        'show': true,
        _id: {
          $ne: this.userId
        },
        'locIndex': {
          $geoWithin: {
            $center: [location, 0.1] 
          }
        }
      },
      {
        limit: 10,
      });
    }
  } else {
    return Meteor.users.find({
      roles: {
        $in: ['driver']
      },
      'show': true
    },
    {
      limit: 10,
    });
  }
});

// server
Meteor.publish("userData", function() {
  if (this.userId) {
    return Meteor.users.find({
      _id: this.userId
    }, {
      fields: {
        'images': 1,
        'others': 1,
        'show': 1,
      }
    });
  } else {
    this.ready();
  }
});

// server
Meteor.publish("userStatus", function() {
  if (this.userId) {
    return Meteor.users.find({
      _id: this.userId
    }, {
      fields: {
        'request': 1,
        'others': 1,
      }
    });
  } else {
    this.ready();
  }
});


// Support for playing D&D: Roll 3d6 for dexterity
Accounts.onCreateUser(function(options, user) {
  //console.log(options, user);
  //  Roles.addUsersToRoles(user._id, options.roles);
  //  user.roles = options.roles;
  user.others = options.others;

  return user;
});
/*
Accounts.validateLoginAttempt(function(options) {
  if (options.user.status.online === true) {
    throw new Meteor.Error("发生错误",
      "你的账号已经在另外地方登录");
    //console.log(options, a, b, c);
    return false;
  }
  return true;
});
*/

Meteor.users.allow({
  insert: function (userId, doc) {
    return true;
  },
  update: function (userId, doc, fields, modifier) {
    return true;
  },
  remove: function (userId, doc) {
    return true;
  }
});

Meteor.methods({
  uploadImage: function(type, path) {
    check(type, String);
    check(path, String);
    //    console.log(type, path);

    var cude = {};
    cude['images.' + type] = path;
    //var set = 'images.' + type;

    Meteor.users.upsert(this.userId, {
      $set: cude
    });
  },

  updateLocation: function(location) {

    if (!this.userId) {
      throw new Meteor.Error("未登录！",
        "必须先登录！");
    }
    /*
    var baiduurl =
      'http://api.map.baidu.com/geocoder/v2/?ak=ZxyGAMuX4h3NA0bl6YDCuuw1&output=json&pois=0&location=' +
      location.lat + ',' + location.lng;

    var userid = this.userId;
    request.post({
      url: baiduurl,
      json: true
    }, Meteor.bindEnvironment(function(error, response, body) {
      //str += '名字:' + user.username + '|';
      if (!error && response.statusCode == 200) {
        Meteor.users.upsert(userid, {
          $set: {
            'formatted_address': body.result.formatted_address
          }
        });
      } else {
        //str += '位置: 未知\n';
        console.log(true, {
          errorMessage: body
        });
      }

    }));*/
    Meteor.users.upsert(this.userId, {
      $set: {
        'location': location,
        'locIndex': [location.lng, location.lat]
      }
    });
  },
  
  updateAddress: function(address) {

    if (!this.userId) {
      throw new Meteor.Error("未登录！",
        "必须先登录！");
    }

    Meteor.users.upsert(this.userId, {
      $set: {
        'formatted_address': address
      }
    });
  },
  updateRole: function(userid, role) {
    console.log(userid, role);
    Roles.addUsersToRoles(userid, [role]);
  },

  changeState: function(state, us) {
    if (this.userId) {
      Meteor.users.upsert(this.userId, {
        $set: {
          'workstate': state
        }
      });
    }
  },
  setRequest: function(userId, value) {
    Meteor.users.upsert(userId, {
      $set: {
        'request': value,
      }
    });
  },
  updateShow: function(value) {
    Meteor.users.update(this.userId, {
      $set: {
        'show': value,
      }
    });
  },
});
